class ImportCoachInfosJob < ApplicationJob
  queue_as :default
  require 'activerecord-import'

  def perform(import_file)
    cards, classhours, del_ids = Array.new(3) {[]}
    CoachClasshour.transaction do
      CSV.foreach(import_file).each_with_index do |row, index|
        if index != 0
          row[2..4].uniq.compact.each do |card|
            del_ids.push(row[0])
            bank, subbranch, cardno = card.split("|")
            cards << CoachBankcard.new(coach_id: row[0], bank: bank, subbranch: subbranch, cardno: cardno)
          end
          CLASSHOURS.each_with_index do |classhour, i|
            if row[5..8][i] && row[5..8][i].to_i > 0
              classhour = CoachClasshour.find_or_initialize_by(coach_id: row[0], classhour: classhour)
              classhour.charge = row[5..8][i]
              classhour.save
            else
              CoachClasshour.where(coach_id: row[0], classhour: classhour).delete_all
            end
          end
        end
      end
    end
    Rails.logger.info "import CoachBankcard: #{cards.size} lines,from ##{del_ids.uniq.size} coaches, ids: #{del_ids.uniq.join(",")}"
    CoachBankcard.where(coach_id: del_ids.uniq).delete_all
    CoachBankcard.import cards
    # CoachClasshour.import classhours, validate: false, on_duplicate_key_update: {constraint_name: :unique_classhour_coach_id, columns: [:charge]}
  end
end
